// 导入 Electron 核心模块
import { app, shell, BrowserWindow, ipcMain, dialog, Notification, nativeTheme, net, clipboard, Tray, Menu, globalShortcut, desktopCapturer, screen, powerSaveBlocker } from 'electron'
import { join, basename } from 'path'
import { promises as fs } from 'fs'
import { EventEmitter } from 'events'
import * as os from 'os'
// 导入 Electron 工具包，提供优化和环境判断功能
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
// 导入应用图标资源
import icon from '../../resources/icon.png?asset'

// 全局变量存储窗口引用
let mainWindow: BrowserWindow | null = null
const childWindows = new Map<string, BrowserWindow>()
let tray: Tray | null = null

// Windows系统专用的屏幕录制配置（必须在app.whenReady()之前调用）
console.log('当前平台:', process.platform)

if (process.platform === 'win32') {
  // Windows特定配置
  app.commandLine.appendSwitch('enable-experimental-web-platform-features')
  app.commandLine.appendSwitch('enable-usermedia-screen-capturing')  
  app.commandLine.appendSwitch('disable-web-security')
  app.commandLine.appendSwitch('allow-running-insecure-content')
  app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors,VizDisplayCompositor')
  app.commandLine.appendSwitch('enable-features', 'DesktopCaptureChangeSource')
  app.commandLine.appendSwitch('disable-gpu-sandbox')
  app.commandLine.appendSwitch('no-sandbox')
  
  console.log('已启用Windows专用屏幕录制配置')
} else {
  // 其他平台配置
  app.commandLine.appendSwitch('enable-experimental-web-platform-features')
  app.commandLine.appendSwitch('enable-usermedia-screen-capturing')
  console.log('已启用通用屏幕录制配置')
}

/**
 * 创建主应用窗口
 * 配置窗口属性、事件监听和内容加载
 */
function createWindow(): void {
  // 创建浏览器窗口实例
  mainWindow = new BrowserWindow({
    width: 900, // 窗口宽度
    height: 670, // 窗口高度
    show: false, // 初始不显示，等待ready-to-show事件
    frame: false, // 完全移除窗口框架，包括标题栏
    autoHideMenuBar: true, // 自动隐藏菜单栏
    // Linux 系统下设置应用图标
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      // 预加载脚本路径，用于安全的渲染进程通信
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false, // 禁用沙盒模式以允许节点集成
      webSecurity: false, // 禁用web安全策略以允许屏幕录制和blob URL
      allowRunningInsecureContent: true, // 允许运行不安全内容
      contextIsolation: true, // 启用上下文隔离
      enableRemoteModule: false, // 禁用远程模块
      nodeIntegration: false, // 禁用节点集成（通过preload脚本提供API）
      // 媒体相关配置
      enableWebSQL: false, // 禁用WebSQL（安全考虑）
      safeDialogs: true, // 启用安全对话框
      safeDialogsMessage: '此应用正在尝试显示对话框', // 安全对话框消息
      // Windows专用配置
      ...(process.platform === 'win32' ? {
        experimentalFeatures: true,
        webgl: true,
        plugins: true,
        // 允许blob和data URL
        allowRunningInsecureContent: true,
        webSecurity: false
      } : {})
    }
  })

  // 窗口准备显示时的事件监听
  mainWindow.on('ready-to-show', () => {
    if (mainWindow) {
      mainWindow.show() // 显示窗口
    }
  })

  // 处理窗口中的链接点击事件
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url) // 使用系统默认浏览器打开外部链接
    return { action: 'deny' } // 阻止在应用内打开新窗口
  })

  // Windows专用权限处理
  mainWindow.webContents.session.setPermissionRequestHandler((webContents, permission, callback, details) => {
    console.log('🔐 [权限请求]', {
      permission,
      requestingOrigin: details?.requestingUrl || 'unknown',
      embeddingOrigin: details?.embeddingOrigin || 'unknown',
      isMainFrame: details?.isMainFrame || false
    })
    
    // 在Windows上，对所有权限请求都返回true
    if (process.platform === 'win32') {
      console.log('✅ [Windows] 自动允许所有权限:', permission)
      callback(true)
      return
    }
    
    // 其他平台的权限处理
    const allowedPermissions = [
      'media', 
      'camera', 
      'microphone', 
      'display-capture',
      'desktop-capture',
      'screen-capture',
      'audio-capture',
      'video-capture',
      'screen-wake-lock',
      'system-wake-lock'
    ]
    
    if (permission === 'media' || permission.includes('capture') || allowedPermissions.includes(permission)) {
      console.log('✅ 允许权限:', permission)
      callback(true)
    } else {
      console.log('✅ 未知权限，但仍然允许:', permission)
      callback(true)
    }
  })

  // 处理权限检查
  mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
    console.log('权限检查:', permission, 'from:', requestingOrigin)
    return true // 允许所有权限检查
  })

  // 设置用户代理以确保兼容性
  mainWindow.webContents.setUserAgent(mainWindow.webContents.getUserAgent() + ' ElectronScreenCapture/1.0')

  // 启用实验性功能
  mainWindow.webContents.session.setPermissionCheckHandler(() => true)
  
  // 处理证书错误
  mainWindow.webContents.session.setCertificateVerifyProc((request, callback) => {
    callback(0) // 忽略证书错误
  })
  
  // 设置CSP来允许blob和data URL（解决视频加载问题）
  mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    const responseHeaders = details.responseHeaders || {}
    
    // 删除可能阻止blob URL的CSP头
    delete responseHeaders['content-security-policy']
    delete responseHeaders['content-security-policy-report-only']
    delete responseHeaders['x-content-security-policy']
    
    // 或者设置宽松的CSP允许blob和data URL
    responseHeaders['content-security-policy'] = [
      "default-src 'self' 'unsafe-inline' 'unsafe-eval' blob: data: http: https:; " +
      "media-src 'self' blob: data: http: https:; " +
      "img-src 'self' blob: data: http: https:; " +
      "connect-src 'self' blob: data: http: https: ws: wss:;"
    ]
    
    callback({ responseHeaders })
  })

  // 基于 electron-vite 的热重载支持
  // 开发环境加载开发服务器URL，生产环境加载本地HTML文件
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

/**
 * 设置所有IPC通信处理
 */
function setupAllIPCHandlers(): void {
  // 1. 应用信息相关
  ipcMain.handle('get-app-version', () => {
    return app.getVersion()
  })

  ipcMain.handle('get-app-info', () => {
    return {
      name: app.getName(),
      version: app.getVersion(),
      isPackaged: app.isPackaged,
      locale: app.getLocale()
    }
  })

  // 2. 窗口控制
  ipcMain.on('window-minimize', () => {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      focusedWindow.minimize()
    }
  })

  ipcMain.on('window-maximize', () => {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      if (focusedWindow.isMaximized()) {
        focusedWindow.unmaximize()
      } else {
        focusedWindow.maximize()
      }
    }
  })

  ipcMain.on('window-toggle-maximize', () => {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      if (focusedWindow.isMaximized()) {
        focusedWindow.unmaximize()
      } else {
        focusedWindow.maximize()
      }
    }
  })

  ipcMain.on('window-close', () => {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      focusedWindow.close()
    }
  })

  ipcMain.on('window-set-always-on-top', (_, flag: boolean) => {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      focusedWindow.setAlwaysOnTop(flag)
    }
  })

  // 3. 应用控制
  ipcMain.on('app-quit', () => {
    app.quit()
  })

  ipcMain.on('app-restart', () => {
    app.relaunch()
    app.exit(0)
  })

  // 4. 系统通知
  ipcMain.on('show-notification', (_, options: { title: string; body: string; icon?: string }) => {
    new Notification({
      title: options.title,
      body: options.body,
      icon: options.icon
    }).show()
  })

  // 5. 主题相关
  ipcMain.handle('get-system-theme', () => {
    return nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
  })

  // 监听主题变化
  nativeTheme.on('updated', () => {
    const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
    // 向所有窗口广播主题变化
    BrowserWindow.getAllWindows().forEach(window => {
      window.webContents.send('theme-changed', theme)
    })
  })

  // 6. 消息广播（渲染进程间通信中转）
  ipcMain.on('broadcast-message', (event, { channel, data, excludeSender = true }) => {
    const allWindows = BrowserWindow.getAllWindows()
    console.log(`[广播消息] 频道: ${channel}, 总窗口数: ${allWindows.length}, 排除发送者: ${excludeSender}`)
    console.log(`[广播消息] 数据:`, data)
    
    allWindows.forEach((window, index) => {
      const isExcluded = excludeSender && window.webContents === event.sender
      console.log(`[广播消息] 窗口${index + 1}: ${isExcluded ? '跳过(发送者)' : '发送'}`)
      
      if (!isExcluded) {
        window.webContents.send(channel, data)
      }
    })
  })

  // 窗口管理相关
  ipcMain.handle('create-child-window', async (_, options = {}) => {
    try {
      const windowId = `child-${Date.now()}`
      const childWindow = new BrowserWindow({
        width: options.width || 800,
        height: options.height || 600,
        show: false,
        // 不设置parent，让子窗口独立显示在任务栏
        parent: undefined,
        modal: false,
        // 支持自定义边框和菜单栏设置
        frame: options.frame !== undefined ? options.frame : true, // 默认有边框
        autoHideMenuBar: options.autoHideMenuBar !== undefined ? options.autoHideMenuBar : false, // 默认显示菜单栏
        title: options.title || '子窗口',
        // 确保在任务栏显示
        skipTaskbar: false,
        // 设置窗口图标（所有平台）
        ...(process.platform === 'linux' && { icon }),
        ...(process.platform === 'win32' && { icon }),
        // 设置窗口的其他属性以确保独立性
        minimizable: true,
        maximizable: true,
        closable: true,
        resizable: true,
        // 确保窗口有独立的标识
        webPreferences: {
          preload: join(__dirname, '../preload/index.js'),
          sandbox: false,
          // 为子窗口添加独立的上下文标识
          additionalArguments: [`--window-type=child`, `--window-id=${windowId}`]
        }
      })

      // 加载子窗口页面（使用路由）
      if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        childWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}?type=child-window&id=${windowId}#/child-window`)
      } else {
        childWindow.loadFile(join(__dirname, '../renderer/index.html'), {
          search: `?type=child-window&id=${windowId}`,
          hash: '#/child-window'
        })
      }

      childWindow.on('ready-to-show', () => {
        childWindow.show()
        // 设置更具体的窗口标题
        const timestamp = new Date().toLocaleTimeString('zh-CN')
        childWindow.setTitle(`${options.title || '子窗口'} - ${timestamp}`)
        
        // 如果是菜单演示窗口，设置演示菜单
        if (options.title && options.title.includes('菜单栏演示')) {
          const demoMenuTemplate = [
            {
              label: '文件',
              submenu: [
                { label: '新建', accelerator: 'Ctrl+N' },
                { label: '打开', accelerator: 'Ctrl+O' },
                { type: 'separator' },
                { label: '退出', accelerator: 'Ctrl+Q', role: 'quit' }
              ]
            },
            {
              label: '编辑',
              submenu: [
                { label: '撤销', accelerator: 'Ctrl+Z', role: 'undo' },
                { label: '重做', accelerator: 'Ctrl+Y', role: 'redo' },
                { type: 'separator' },
                { label: '复制', accelerator: 'Ctrl+C', role: 'copy' },
                { label: '粘贴', accelerator: 'Ctrl+V', role: 'paste' }
              ]
            },
            {
              label: '查看',
              submenu: [
                { label: '重新加载', accelerator: 'Ctrl+R', role: 'reload' },
                { label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
                { type: 'separator' },
                { label: '放大', accelerator: 'Ctrl+Plus', role: 'zoomIn' },
                { label: '缩小', accelerator: 'Ctrl+-', role: 'zoomOut' },
                { label: '实际大小', accelerator: 'Ctrl+0', role: 'resetZoom' }
              ]
            },
            {
              label: '帮助',
              submenu: [
                { 
                  label: '关于菜单演示', 
                  click: () => {
                    childWindow.webContents.executeJavaScript(`
                      alert('这是一个菜单栏演示窗口！\\n\\n您可以看到完整的应用菜单，包括：\\n- 文件菜单\\n- 编辑菜单\\n- 查看菜单\\n- 帮助菜单\\n\\n所有菜单项都具有相应的快捷键。')
                    `)
                  }
                }
              ]
            }
          ]
          
          // 为这个子窗口设置专门的菜单
          const demoMenu = Menu.buildFromTemplate(demoMenuTemplate)
          Menu.setApplicationMenu(demoMenu)
          
          console.log('已为菜单演示窗口设置演示菜单')
        }
      })

      childWindow.on('closed', () => {
        childWindows.delete(windowId)
        // 通知主窗口子窗口已关闭
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.webContents.send('child-window-closed', { windowId })
        }
      })

      // 存储窗口引用
      childWindows.set(windowId, childWindow)

      return { success: true, windowId }
    } catch (error) {
      console.error('创建子窗口失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  ipcMain.handle('get-window-list', () => {
    const windows = BrowserWindow.getAllWindows().map(window => ({
      id: window.id,
      title: window.getTitle(),
      isVisible: window.isVisible(),
      isMinimized: window.isMinimized(),
      isMaximized: window.isMaximized()
    }))
    return windows
  })

  ipcMain.on('close-child-window', (_, windowId: string) => {
    const childWindow = childWindows.get(windowId)
    if (childWindow && !childWindow.isDestroyed()) {
      childWindow.close()
    }
  })

  ipcMain.on('focus-window', (_, windowId: number) => {
    const window = BrowserWindow.fromId(windowId)
    if (window) {
      window.focus()
    }
  })

  // 7. 存储相关（简单键值对存储）
  const storage = new Map<string, any>()
  
  ipcMain.handle('storage-get', (_, key: string) => {
    return storage.get(key)
  })

  ipcMain.handle('storage-set', (_, key: string, value: any) => {
    storage.set(key, value)
    return true
  })

  ipcMain.handle('storage-delete', (_, key: string) => {
    return storage.delete(key)
  })

  ipcMain.handle('storage-clear', () => {
    storage.clear()
    return true
  })

  ipcMain.handle('storage-keys', () => {
    return Array.from(storage.keys())
  })

  // 8. 网络检测
  ipcMain.handle('check-network', async () => {
    try {
      const isOnline = await net.isOnline()
      return { online: isOnline }
    } catch (error) {
      return { 
        online: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  // 9. 剪贴板操作
  ipcMain.handle('clipboard-read-text', () => {
    return clipboard.readText()
  })

  ipcMain.handle('clipboard-write-text', (_, text: string) => {
    clipboard.writeText(text)
    return true
  })

  // 10. 自定义事件系统
  const eventEmitter = new EventEmitter()
  
  ipcMain.on('emit-custom-event', (event, { eventName, data }) => {
    eventEmitter.emit(eventName, data, event.sender)
  })

  ipcMain.on('listen-custom-event', (event, eventName: string) => {
    const listener = (data: any, sender: any) => {
      if (sender !== event.sender) {
        event.sender.send('custom-event-received', { eventName, data })
      }
    }
    eventEmitter.on(eventName, listener)
    
    // 清理监听器
    event.sender.on('destroyed', () => {
      eventEmitter.off(eventName, listener)
    })
  })

  // =========================
  // 系统集成功能处理器
  // =========================

  // 系统托盘相关
  ipcMain.handle('system-create-tray', async (_, options = {}) => {
    try {
      if (tray) {
        tray.destroy()
      }

      tray = new Tray(icon)
      tray.setToolTip(options.tooltip || 'yuCloudEle')

      // 创建默认托盘菜单
      const contextMenu = Menu.buildFromTemplate([
        {
          label: '显示主窗口',
          click: () => {
            if (mainWindow) {
              if (mainWindow.isMinimized()) mainWindow.restore()
              mainWindow.show()
              mainWindow.focus()
            }
          }
        },
        {
          label: '隐藏窗口',
          click: () => {
            if (mainWindow) mainWindow.hide()
          }
        },
        { type: 'separator' },
        {
          label: '发送通知',
          click: () => {
            const notification = new Notification({
              title: 'yuCloudEle',
              body: '这是来自系统托盘的通知！',
              icon: icon
            })
            notification.show()
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          click: () => app.quit()
        }
      ])

      tray.setContextMenu(contextMenu)

      // 托盘点击事件
      tray.on('click', () => {
        if (mainWindow) {
          if (mainWindow.isVisible()) {
            mainWindow.hide()
          } else {
            mainWindow.show()
            mainWindow.focus()
          }
        }
      })

      console.log('系统托盘创建成功')
      return { success: true, message: '系统托盘创建成功' }
    } catch (error) {
      console.error('创建系统托盘失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  ipcMain.handle('system-destroy-tray', async () => {
    try {
      if (tray) {
        tray.destroy()
        tray = null
        console.log('系统托盘已销毁')
        return { success: true, message: '系统托盘已销毁' }
      }
      return { success: false, message: '托盘不存在' }
    } catch (error) {
      console.error('销毁系统托盘失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  ipcMain.handle('system-update-tray-menu', async (_, menuTemplate) => {
    try {
      if (!tray) {
        return { success: false, message: '托盘不存在' }
      }

      // 转换菜单模板
      const contextMenu = Menu.buildFromTemplate(menuTemplate.map((item: any) => {
        if (item.type === 'separator') {
          return { type: 'separator' }
        }
        
        return {
          label: item.label,
          click: () => {
            // 根据action执行相应操作
            switch (item.action) {
              case 'show':
                if (mainWindow) {
                  mainWindow.show()
                  mainWindow.focus()
                }
                break
              case 'hide':
                if (mainWindow) mainWindow.hide()
                break
              case 'quit':
                app.quit()
                break
              case 'notify':
                const notification = new Notification({
                  title: 'yuCloudEle',
                  body: '托盘菜单通知！',
                  icon: icon
                })
                notification.show()
                break
              default:
                console.log('托盘菜单动作:', item.action)
            }
          }
        }
      }))

      tray.setContextMenu(contextMenu)
      return { success: true, message: '托盘菜单更新成功' }
    } catch (error) {
      console.error('更新托盘菜单失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  ipcMain.handle('system-get-tray-status', async () => {
    return { 
      created: tray !== null,
      destroyed: tray === null
    }
  })

  // 全局快捷键相关  
  ipcMain.handle('system-register-shortcut', async (_, { accelerator, action }) => {
    try {
      const ret = globalShortcut.register(accelerator, () => {
        console.log(`全局快捷键触发: ${accelerator} -> ${action}`)
        
        // 执行相应操作
        switch (action) {
          case 'show-hide-window': {
            if (mainWindow && !mainWindow.isDestroyed()) {
              const isVisible = mainWindow.isVisible()
              const isMinimized = mainWindow.isMinimized()
              
              console.log(`窗口状态检查: visible=${isVisible}, minimized=${isMinimized}`)
              
              if (isVisible && !isMinimized) {
                // 窗口可见且未最小化，隐藏窗口
                console.log('隐藏窗口')
                mainWindow.hide()
              } else {
                // 窗口隐藏或最小化，显示并聚焦窗口
                console.log('显示并聚焦窗口')
                if (isMinimized) {
                  mainWindow.restore()
                }
                mainWindow.show()
                mainWindow.focus()
                
                // 在macOS上确保窗口真正获得焦点
                if (process.platform === 'darwin') {
                  app.focus({ steal: true })
                }
              }
            } else {
              console.error('主窗口不存在或已销毁')
            }
            break
          }
          case 'show-notification': {
            const notification = new Notification({
              title: 'yuCloudEle',
              body: `快捷键 ${accelerator} 被触发！`,
              icon: icon,
              silent: false, // 快捷键触发的通知默认有声音
              sound: process.platform === 'win32' ? 'default' : undefined
            })
            notification.show()
            console.log(`快捷键通知已发送: ${accelerator}`)
            break
          }
          case 'custom-action':
          default:
            // 发送事件到渲染进程
            if (mainWindow) {
              mainWindow.webContents.send('global-shortcut-triggered', { accelerator, action })
            }
            break
        }
      })

      if (!ret) {
        return { success: false, message: '快捷键注册失败，可能已被占用' }
      }

      console.log(`全局快捷键注册成功: ${accelerator}`)
      return { success: true, message: `快捷键 ${accelerator} 注册成功` }
    } catch (error) {
      console.error('注册全局快捷键失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  ipcMain.handle('system-unregister-shortcut', async (_, accelerator) => {
    try {
      globalShortcut.unregister(accelerator)
      console.log(`全局快捷键注销成功: ${accelerator}`)
      return { success: true, message: `快捷键 ${accelerator} 注销成功` }
    } catch (error) {
      console.error('注销全局快捷键失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  // 系统通知相关
  ipcMain.handle('system-show-notification', async (_, options) => {
    try {
      // 方案1: 使用系统beep声音（作为备用）
      const playSystemBeep = () => {
        try {
          shell.beep()
          console.log('播放系统提示音')
        } catch (error) {
          console.error('播放系统提示音失败:', error)
        }
      }

      const notificationOptions: any = {
        title: options.title || 'yuCloudEle',
        body: options.body || '',
        icon: icon,
        silent: options.silent === true, // 明确处理 silent 属性
      }

      // 根据平台设置不同的通知选项
      if (process.platform === 'win32') {
        // Windows 平台特殊处理
        if (!options.silent) {
          notificationOptions.sound = 'default'
        }
      } else if (process.platform === 'darwin') {
        // macOS 平台
        if (!options.silent) {
          notificationOptions.sound = 'default'
        }
      } else if (process.platform === 'linux') {
        // Linux 平台使用 urgency
        notificationOptions.urgency = options.urgency || 'normal'
      }

      // 紧急通知的额外处理
      if (options.urgent || options.urgency === 'critical') {
        notificationOptions.urgency = 'critical'
        // 紧急通知强制播放声音（除非明确设置为静音）
        if (!options.silent) {
          notificationOptions.silent = false
          if (process.platform === 'win32') {
            notificationOptions.sound = 'default'
          } else if (process.platform === 'darwin') {
            notificationOptions.sound = 'default'
          }
        }
      }

      console.log('创建通知，配置:', notificationOptions)

      const notification = new Notification(notificationOptions)

      // 如果不是静音模式，播放系统提示音作为备用
      if (!options.silent) {
        // 延迟播放系统提示音，确保通知已显示
        setTimeout(() => {
          playSystemBeep()
        }, 100)
      }

      notification.show()
      
      // 添加通知事件监听
      notification.on('show', () => {
        console.log('系统通知已显示')
        // 通知显示时再次尝试播放声音
        if (!options.silent && (options.urgent || options.urgency === 'critical')) {
          setTimeout(() => {
            playSystemBeep()
          }, 50)
        }
      })
      
      notification.on('click', () => {
        console.log('用户点击了通知')
        // 点击通知时聚焦主窗口
        if (mainWindow && !mainWindow.isDestroyed()) {
          if (mainWindow.isMinimized()) {
            mainWindow.restore()
          }
          mainWindow.focus()
        }
      })
      
      notification.on('close', () => {
        console.log('通知已关闭')
      })

      return { success: true, message: '通知发送成功' }
    } catch (error) {
      console.error('发送系统通知失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  // 应用菜单相关
  ipcMain.handle('system-set-app-menu', async (_, template) => {
    try {
      if (template === null) {
        // 恢复默认菜单
        Menu.setApplicationMenu(null)
      } else {
        // 处理菜单模板，为每个菜单项添加点击处理
        const processedTemplate = template.map((menu: any) => ({
          ...menu,
          submenu: menu.submenu?.map((item: any) => {
            if (item.type === 'separator') return item
            
            return {
              ...item,
              click: () => {
                // 发送菜单点击事件到渲染进程
                if (mainWindow && !mainWindow.isDestroyed()) {
                  mainWindow.webContents.send('menu-action', {
                    action: item.action || item.role,
                    label: item.label,
                    accelerator: item.accelerator
                  })
                }
                
                // 处理内置角色
                if (item.role) {
                  handleMenuRole(item.role)
                }
              }
            }
          })
        }))
        
        const menu = Menu.buildFromTemplate(processedTemplate)
        Menu.setApplicationMenu(menu)
      }
      return { success: true, message: '应用菜单设置成功' }
    } catch (error) {
      console.error('设置应用菜单失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  // 处理菜单角色
  function handleMenuRole(role: string) {
    switch (role) {
      case 'quit':
        app.quit()
        break
      case 'minimize':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.minimize()
        }
        break
      case 'close':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.close()
        }
        break
      case 'reload':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.reload()
        }
        break
      case 'forceReload':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.webContents.reloadIgnoringCache()
        }
        break
      case 'toggleDevTools':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.webContents.toggleDevTools()
        }
        break
      case 'resetZoom':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.webContents.setZoomLevel(0)
        }
        break
      case 'zoomIn':
        if (mainWindow && !mainWindow.isDestroyed()) {
          const currentZoom = mainWindow.webContents.getZoomLevel()
          mainWindow.webContents.setZoomLevel(currentZoom + 0.5)
        }
        break
      case 'zoomOut':
        if (mainWindow && !mainWindow.isDestroyed()) {
          const currentZoom = mainWindow.webContents.getZoomLevel()
          mainWindow.webContents.setZoomLevel(currentZoom - 0.5)
        }
        break
      case 'togglefullscreen':
        if (mainWindow && !mainWindow.isDestroyed()) {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
        break
    }
  }

  ipcMain.handle('system-set-menubar-visibility', async (_, visible) => {
    try {
      if (mainWindow) {
        // 对于无边框窗口，需要同时设置 autoHideMenuBar 和 MenuBarVisibility
        if (visible) {
          // 显示菜单栏：禁用自动隐藏，设置为可见
          mainWindow.setAutoHideMenuBar(false)
          mainWindow.setMenuBarVisibility(true)
          
          // 在某些平台上，可能需要重新设置菜单
          const currentMenu = Menu.getApplicationMenu()
          if (currentMenu) {
            Menu.setApplicationMenu(currentMenu)
          }
        } else {
          // 隐藏菜单栏：启用自动隐藏，设置为不可见
          mainWindow.setMenuBarVisibility(false)
          mainWindow.setAutoHideMenuBar(true)
        }
        
        console.log(`菜单栏设置: visible=${visible}, autoHide=${!visible}`)
        return { success: true, message: `菜单栏已${visible ? '显示' : '隐藏'}` }
      }
      return { success: false, message: '主窗口不存在' }
    } catch (error) {
      console.error('设置菜单栏可见性失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  // 协议注册相关
  ipcMain.handle('system-register-protocol', async (_, protocol) => {
    try {
      if (app.isDefaultProtocolClient(protocol)) {
        return { success: true, message: `协议 ${protocol} 已注册` }
      }

      const success = app.setAsDefaultProtocolClient(protocol)
      if (success) {
        console.log(`协议注册成功: ${protocol}://`)
        return { success: true, message: `协议 ${protocol} 注册成功` }
      } else {
        return { success: false, message: '协议注册失败' }
      }
    } catch (error) {
      console.error('注册协议失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  // 开机自启动相关
  ipcMain.handle('system-set-auto-launch', async (_, enabled) => {
    try {
      const appPath = app.getPath('exe')
      
      if (enabled) {
        app.setLoginItemSettings({
          openAtLogin: true,
          path: appPath
        })
      } else {
        app.setLoginItemSettings({
          openAtLogin: false
        })
      }

      const settings = app.getLoginItemSettings()
      return { 
        success: true, 
        enabled: settings.openAtLogin,
        path: settings.executableWillLaunchAtLogin ? appPath : null,
        message: `开机自启动已${enabled ? '启用' : '禁用'}`
      }
    } catch (error) {
      console.error('设置开机自启动失败:', error)
      return { 
        success: false, 
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })

  ipcMain.handle('system-get-auto-launch-status', async () => {
    try {
      const settings = app.getLoginItemSettings()
      return {
        enabled: settings.openAtLogin,
        path: settings.executableWillLaunchAtLogin ? app.getPath('exe') : null
      }
    } catch (error) {
      console.error('获取开机自启动状态失败:', error)
      return { 
        enabled: false, 
        path: null,
        error: error instanceof Error ? error.message : String(error) 
      }
    }
  })
}

/**
 * 设置文件操作相关的IPC处理
 */
function setupFileOperations(): void {
  // 显示打开文件对话框
  ipcMain.handle('show-open-dialog', async (_, options = {}) => {
    try {
      const result = await dialog.showOpenDialog({
        properties: ['openFile'],
        filters: [
          { name: 'Text Files', extensions: ['txt', 'md', 'json'] },
          { name: 'All Files', extensions: ['*'] }
        ],
        ...options
      })
      return result
    } catch (error) {
      console.error('打开文件对话框失败:', error)
      return { canceled: true, filePaths: [] }
    }
  })

  // 显示保存文件对话框
  ipcMain.handle('show-save-dialog', async (_, options = {}) => {
    try {
      const result = await dialog.showSaveDialog({
        filters: [
          { name: 'Text Files', extensions: ['txt'] },
          { name: 'JSON Files', extensions: ['json'] },
          { name: 'All Files', extensions: ['*'] }
        ],
        ...options
      })
      return result
    } catch (error) {
      console.error('保存文件对话框失败:', error)
      return { canceled: true, filePath: '' }
    }
  })

  // 读取文件内容
  ipcMain.handle('read-file', async (_, filePath: string) => {
    try {
      const content = await fs.readFile(filePath, 'utf8')
      const stats = await fs.stat(filePath)
      return {
        success: true,
        content,
        size: stats.size,
        modified: stats.mtime,
        name: basename(filePath)
      }
    } catch (error) {
      console.error('读取文件失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
        content: null
      }
    }
  })

  // 写入文件内容
  ipcMain.handle('write-file', async (_, filePath: string, content: string) => {
    try {
      await fs.writeFile(filePath, content, 'utf8')
      return {
        success: true,
        message: '文件保存成功'
      }
    } catch (error) {
      console.error('写入文件失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 获取文件信息
  ipcMain.handle('get-file-info', async (_, filePath: string) => {
    try {
      const stats = await fs.stat(filePath)
      return {
        success: true,
        info: {
          size: stats.size,
          created: stats.birthtime,
          modified: stats.mtime,
          isFile: stats.isFile(),
          isDirectory: stats.isDirectory()
        }
      }
    } catch (error) {
      console.error('获取文件信息失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 硬件访问相关的IPC处理器
  
  // 屏幕截图相关
  ipcMain.handle('hardware-capture-screen', async () => {
    try {
      const sources = await desktopCapturer.getSources({
        types: ['screen'],
        thumbnailSize: { width: 1920, height: 1080 }
      })
      
      if (sources.length > 0) {
        const primaryScreen = sources[0]
        const dataUrl = primaryScreen.thumbnail.toDataURL()
        const size = primaryScreen.thumbnail.getSize()
        
        return {
          success: true,
          dataUrl,
          width: size.width,
          height: size.height
        }
      } else {
        return {
          success: false,
          error: '没有找到可用的屏幕源'
        }
      }
    } catch (error) {
      console.error('屏幕截图失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  ipcMain.handle('hardware-capture-window', async (_, windowId) => {
    try {
      const sources = await desktopCapturer.getSources({
        types: ['window'],
        thumbnailSize: { width: 1920, height: 1080 }
      })
      
      let targetSource = sources[0] // 默认使用第一个窗口
      if (windowId) {
        const foundSource = sources.find(source => source.id === windowId)
        if (foundSource) targetSource = foundSource
      }
      
      if (targetSource) {
        const dataUrl = targetSource.thumbnail.toDataURL()
        const size = targetSource.thumbnail.getSize()
        
        return {
          success: true,
          dataUrl,
          width: size.width,
          height: size.height
        }
      } else {
        return {
          success: false,
          error: '没有找到可用的窗口源'
        }
      }
    } catch (error) {
      console.error('窗口截图失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  ipcMain.handle('hardware-capture-source', async (_, sourceId) => {
    try {
      const sources = await desktopCapturer.getSources({
        types: ['screen', 'window'],
        thumbnailSize: { width: 1920, height: 1080 }
      })
      
      const targetSource = sources.find(source => source.id === sourceId)
      
      if (targetSource) {
        const dataUrl = targetSource.thumbnail.toDataURL()
        const size = targetSource.thumbnail.getSize()
        
        return {
          success: true,
          dataUrl,
          width: size.width,
          height: size.height
        }
      } else {
        return {
          success: false,
          error: `没有找到ID为 ${sourceId} 的屏幕源`
        }
      }
    } catch (error) {
      console.error('截取指定源失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  ipcMain.handle('hardware-get-screen-sources', async () => {
    try {
      console.log('🔍 [Windows] 开始获取屏幕源...')
      
      // Windows专用的屏幕源获取，使用更宽松的设置
      const sources = await desktopCapturer.getSources({
        types: ['screen', 'window'],
        thumbnailSize: { width: 150, height: 100 },
        fetchWindowIcons: false
      })
      
      console.log('✅ [Windows] 获取到源:', sources.length, '个')
      
      // 过滤并标记可捕获的源
      const result = sources.map(source => {
        const isScreen = source.id.startsWith('screen:') || source.name.includes('Screen') || source.name.includes('屏幕') || source.name.includes('整个屏幕')
        
        // 检查源是否可能不可捕获（基于名称模式）
        const suspiciousPatterns = [
          'DRM',
          'Protected',
          'Secure',
          'Netflix',
          'Prime Video',
          'Disney+',
          'Hulu'
        ]
        const mightNotBeCapturable = suspiciousPatterns.some(pattern => 
          source.name.toLowerCase().includes(pattern.toLowerCase())
        )
        
        console.log(`📺 源: ${source.name} (${source.id}) - 类型: ${isScreen ? 'screen' : 'window'}${mightNotBeCapturable ? ' [可能受保护]' : ''}`)
        
        return {
          id: source.id,
          name: source.name,
          type: isScreen ? 'screen' : 'window',
          thumbnail: source.thumbnail ? source.thumbnail.toDataURL() : '',
          display_id: source.display_id,
          appIcon: source.appIcon ? source.appIcon.toDataURL() : undefined,
          mightNotBeCapturable
        }
      })
      
      // 优先返回屏幕源，并将可能受保护的源排到后面
      const sortedResult = result.sort((a, b) => {
        if (a.type === 'screen' && b.type !== 'screen') return -1
        if (a.type !== 'screen' && b.type === 'screen') return 1
        if (a.mightNotBeCapturable && !b.mightNotBeCapturable) return 1
        if (!a.mightNotBeCapturable && b.mightNotBeCapturable) return -1
        return 0
      })
      
      console.log('📋 [Windows] 排序后的源列表:', sortedResult.length, '个')
      return sortedResult
      
    } catch (error: any) {
      console.error('❌ [Windows] 获取屏幕源失败:', error)
      console.error('错误详情:', {
        name: error.name,
        message: error.message,
        code: error.code
      })
      
      return []
    }
  })

  // 测试屏幕源是否可捕获（修复IPC错误）
  ipcMain.handle('hardware-test-source-capturable', async (_, sourceId: string) => {
    try {
      console.log('🧪 [Windows] 测试源是否可捕获:', sourceId)
      
      if (!sourceId || typeof sourceId !== 'string') {
        throw new Error('无效的源ID')
      }
      
      // 使用desktopCapturer直接测试，避免IPC问题
      const sources = await desktopCapturer.getSources({
        types: ['screen', 'window'],
        thumbnailSize: { width: 50, height: 50 }
      })
      
      const targetSource = sources.find(s => s.id === sourceId)
      if (!targetSource) {
        throw new Error('源不存在')
      }
      
      console.log('✅ [Windows] 源存在且可访问:', sourceId)
      return { capturable: true, error: null }
      
    } catch (error: any) {
      console.log('❌ [Windows] 源测试失败:', sourceId, error.message)
      return { capturable: false, error: error.message }
    }
  })

  // Windows专用的直接屏幕录制方法
  ipcMain.handle('hardware-start-windows-screen-recording', async () => {
    try {
      console.log('🎬 [Windows] 开始直接屏幕录制...')
      
      // 获取主屏幕源
      const sources = await desktopCapturer.getSources({
        types: ['screen'],
        thumbnailSize: { width: 150, height: 100 }
      })
      
      if (sources.length === 0) {
        throw new Error('未找到屏幕源')
      }
      
      const primaryScreen = sources[0] // 获取第一个屏幕（通常是主屏幕）
      console.log('📺 [Windows] 选择屏幕:', primaryScreen.name, primaryScreen.id)
      
      return {
        success: true,
        sourceId: primaryScreen.id,
        sourceName: primaryScreen.name,
        message: '屏幕源已准备就绪'
      }
      
    } catch (error: any) {
      console.error('❌ [Windows] 屏幕录制准备失败:', error)
      return {
        success: false,
        error: error.message,
        message: '无法准备屏幕录制'
      }
    }
  })

  // 屏幕录制相关 (简化实现)
  ipcMain.handle('hardware-start-screen-recording', async (_, options = {}) => {
    try {
      // 这里只是一个简化的实现，实际的屏幕录制需要更复杂的逻辑
      console.log('开始屏幕录制', options)
      return {
        success: true,
        message: '屏幕录制已开始（演示模式）'
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  ipcMain.handle('hardware-stop-screen-recording', async () => {
    try {
      console.log('停止屏幕录制')
      return {
        success: true,
        filePath: 'recording.mp4',
        message: '屏幕录制已停止（演示模式）'
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 显示器信息
  ipcMain.handle('hardware-get-display-info', async () => {
    try {
      const displays = screen.getAllDisplays()
      return displays.map(display => ({
        id: display.id,
        bounds: display.bounds,
        workArea: display.workArea,
        scaleFactor: display.scaleFactor,
        rotation: display.rotation
      }))
    } catch (error) {
      console.error('获取显示器信息失败:', error)
      return []
    }
  })

  // 电源信息 (如果可用)
  ipcMain.handle('hardware-get-power-info', async () => {
    try {
      // 注意：powerMonitor在某些系统上可能不可用
      return {
        batteryLevel: 0.8, // 演示数据
        charging: false,
        pluggedIn: true
      }
    } catch (error) {
      console.error('获取电源信息失败:', error)
      return {
        batteryLevel: null,
        charging: null,
        pluggedIn: null
      }
    }
  })

  // 摄像头和麦克风相关 (简化实现)
  ipcMain.handle('hardware-get-camera-devices', async () => {
    try {
      // 在实际应用中，需要使用 navigator.mediaDevices 或其他方法获取设备列表
      return [
        { deviceId: 'default', label: '默认摄像头' },
        { deviceId: 'camera1', label: '前置摄像头' },
        { deviceId: 'camera2', label: '后置摄像头' }
      ]
    } catch (error) {
      return []
    }
  })

  ipcMain.handle('hardware-get-microphone-devices', async () => {
    try {
      return [
        { deviceId: 'default', label: '默认麦克风' },
        { deviceId: 'mic1', label: '内置麦克风' },
        { deviceId: 'mic2', label: '外置麦克风' }
      ]
    } catch (error) {
      return []
    }
  })

  // 其他硬件相关的简化实现
  ipcMain.handle('hardware-start-camera', async (_, deviceId) => {
    console.log('启动摄像头:', deviceId)
    return { success: true, message: '摄像头已启动（演示模式）' }
  })

  ipcMain.handle('hardware-stop-camera', async () => {
    console.log('停止摄像头')
    return { success: true, message: '摄像头已停止' }
  })

  ipcMain.handle('hardware-start-microphone', async (_, deviceId) => {
    console.log('启动麦克风:', deviceId)
    return { success: true, message: '麦克风已启动（演示模式）' }
  })

  ipcMain.handle('hardware-stop-microphone', async () => {
    console.log('停止麦克风')
    return { success: true, message: '麦克风已停止' }
  })

  // 图片保存
  ipcMain.handle('hardware-save-image', async (_, dataUrl: string, fileName: string) => {
    try {
      const base64Data = dataUrl.replace(/^data:image\/\w+;base64,/, '')
      const buffer = Buffer.from(base64Data, 'base64')
      
      const { filePath } = await dialog.showSaveDialog(mainWindow!, {
        defaultPath: fileName,
        filters: [
          { name: 'Images', extensions: ['png', 'jpg', 'jpeg'] }
        ]
      })

      if (filePath) {
        await fs.writeFile(filePath, buffer)
        return { success: true, path: filePath }
      }
      
      return { success: false, error: '用户取消保存' }
    } catch (error: any) {
      console.error('保存图片失败:', error)
      return { success: false, error: error.message }
    }
  })

  // 音频保存 (简化实现，实际应用中需要更复杂的音频处理)
  ipcMain.handle('hardware-save-audio', async (_, audioBlob: any, fileName: string) => {
    try {
      const { filePath } = await dialog.showSaveDialog(mainWindow!, {
        defaultPath: fileName,
        filters: [
          { name: 'Audio', extensions: ['wav', 'mp3', 'webm'] }
        ]
      })

      if (filePath) {
        // 在实际应用中，这里需要将 Blob 转换为文件
        return { success: true, path: filePath, message: '音频保存功能需要更完善的实现' }
      }
      
      return { success: false, error: '用户取消保存' }
    } catch (error: any) {
      console.error('保存音频失败:', error)
      return { success: false, error: error.message }
    }
  })

  // 系统信息
  ipcMain.handle('hardware-get-system-info', async () => {
    try {
      return {
        platform: os.platform(),
        arch: os.arch(),
        version: os.release(),
        hostname: os.hostname(),
        uptime: os.uptime()
      }
    } catch (error: any) {
      console.error('获取系统信息失败:', error)
      return { error: error.message }
    }
  })

  // CPU信息
  ipcMain.handle('hardware-get-cpu-info', async () => {
    try {
      return os.cpus()
    } catch (error: any) {
      console.error('获取CPU信息失败:', error)
      return { error: error.message }
    }
  })

  // 内存信息
  ipcMain.handle('hardware-get-memory-info', async () => {
    try {
      const total = os.totalmem()
      const free = os.freemem()
      const used = total - free
      const percentage = Math.round((used / total) * 100)
      
      return {
        total,
        free,
        used,
        percentage
      }
    } catch (error: any) {
      console.error('获取内存信息失败:', error)
      return { error: error.message }
    }
  })

  // 防止系统休眠
  ipcMain.handle('hardware-prevent-system-sleep', async () => {
    try {
      const id = powerSaveBlocker.start('prevent-display-sleep')
      console.log('已防止系统休眠, ID:', id)
      return { success: true, id }
    } catch (error: any) {
      console.error('防止系统休眠失败:', error)
      return { success: false, error: error.message }
    }
  })

  // 允许系统休眠
  ipcMain.handle('hardware-allow-system-sleep', async () => {
    try {
      // 在实际应用中，这里应该停止所有活跃的 powerSaveBlocker
      // 由于我们没有存储ID，这里只是示例实现
      console.log('允许系统休眠')
      return { success: true, message: '已允许系统休眠' }
    } catch (error: any) {
      console.error('允许系统休眠失败:', error)
      return { success: false, error: error.message }
    }
  })
}

/**
 * 应用初始化完成事件
 * Electron 完成初始化并准备创建浏览器窗口时调用
 * 某些 API 只能在此事件发生后使用
 */
app.whenReady().then(() => {
  // 设置 Windows 系统的应用用户模型 ID
  electronApp.setAppUserModelId('com.electron')

  // 设置默认session的权限
  const { session } = require('electron')
  const defaultSession = session.defaultSession
  
  // 允许不安全的内容
  defaultSession.allowNTLMCredentialsForDomains('*')
  
  // 设置默认权限处理
  defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
    console.log('默认session权限请求:', permission)
    callback(true) // 允许所有权限
  })

  // 在开发环境中默认使用 F12 开启/关闭开发者工具
  // 在生产环境中忽略 Ctrl+R 刷新快捷键
  // 详见: https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
    
    // 为新窗口设置权限
    window.webContents.session.setPermissionRequestHandler((webContents, permission, callback) => {
      console.log('新窗口权限请求:', permission)
      callback(true)
    })
  })

  // IPC 通信测试 - 监听来自渲染进程的 'ping' 消息
  ipcMain.on('ping', () => console.log('pong'))

  // 设置所有IPC通信处理
  setupAllIPCHandlers()

  // 文件操作相关的IPC处理
  setupFileOperations()

  // 创建主窗口
  createWindow()

  /**
   * macOS 系统特定行为
   * 在 macOS 中，当点击 dock 图标且没有其他窗口打开时，
   * 通常会重新创建一个窗口
   */
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

/**
 * 所有窗口关闭事件处理
 * 在 macOS 以外的平台上，当所有窗口关闭时退出应用
 * 在 macOS 中，应用和菜单栏通常保持活动状态，直到用户使用 Cmd + Q 显式退出
 */
app.on('window-all-closed', () => {
  // 清理全局快捷键
  globalShortcut.unregisterAll()
  
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

/**
 * 应用即将退出事件处理
 * 清理所有资源
 */
app.on('before-quit', () => {
  // 清理全局快捷键
  globalShortcut.unregisterAll()
  console.log('应用退出前清理完成')
})

/**
 * 在此文件中可以包含应用的其他主进程代码
 * 也可以将它们放在单独的文件中并在此处引入
 */
